<?php

namespace App\Http\Controllers\Frontend;


use App\Logics\ArticleLogic;
use App\Logics\DomainLogic;
use App\Logics\UserLogic;
use App\Logics\WordLogic;
use App\Models\Article;
use App\Service\Curl;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redirect;
use QL\QueryList;

class HomeController extends BaseController
{
    // 首页 初始化
    public function initialize()
    {
        // 这里是测试
        parent::initialize();
    }

    // 首页
    public function index()
    {
        $option  = $this->optLogic();
        $article = new ArticleLogic();
        $logic   = new DomainLogic();

        // 获取所有的频道 和 关键词
        $domain  = $logic->getAllDomain();
        $keyword = $logic->allKeyword();

        // 总数据量
        $total = $article->dateCount();

        // 今天数据量
        $cToday = strtotime(date('Y-m-d'));
        $today  = $article->dateCount($cToday);

        // 昨天数据量
        $cYeday = strtotime("-1 day");
        $cYeday = $cToday - 86400;
        $yeday  = $article->dateCount($cYeday);

        // 公告数量
        $noticeNumber = $article->siteCount(13);

        // 昨天的word
        //$cYedate = "2024-3-4";
        //$cYedate = date("Y-m-d", $cYeday);
        //$newfile = app()->basePath().'/public/'.'date/易见舆情日报'.$cYedate.'.docx';  // 新文件名
        //$is_word = is_file($newfile) ? true : false;
        $cYedate = date("Y-m-d", $cYeday);
        $is_word = true;  // true：不生成Word

        // 传递数据
        $option->assign('keywords', $keyword);
        $option->assign('is_word', $is_word);
        $option->assign('yesdate', $cYedate);
        $option->assign('sites', $domain);
        $option->assign('totalNumber', $total);
        $option->assign('todayNumber', $today);
        $option->assign('yedayNumber', $yeday);
        $option->assign('noticeNumber', $noticeNumber);

        return $option->dispaly('pc.index',[],false);
    }

    // 登录页面
    public function login()
    {
        // 如果已经登录
        if($this->myUid){
            header("Location: /");
            die;
        }

        $option = $this->optLogic();

        return $option->dispaly('pc.login',[],false);
    }

    // 退出
    public function logout()
    {
        // 删除cookie后需要重新定向
        $cookie = Cookie::forget('user');
        session(['uid' => 0]);

        return Redirect::route('frontend')->withCookie($cookie);


        // 删除 cookie
        //$this->request->session()->forget('user');
        //Cookie::forget('user');
        Cookie::queue(Cookie::forget('user'));
        Cookie::queue(Cookie::make('user', null, -10));
        //Cookie::queue('user', '[]', -10);

        // 跳转 首页
        $url = htmlUrl('/index');
        //header("refresh:3;Location: ".$url);
        //header("refresh:0.2;".$url);
        echo '<script> window.location.href = "'.$url.'";</script>';
        exit;
        //return $this->dispaly('user.login');
    }

    // 获取数据
    public function onLists()
    {
        $option  = $this->optLogic();
        $article = new ArticleLogic();

        // 执行
        $result  = $article->onLists();
        $is_page = $option->getData('is_page', 0, 'intval');

        // 如果是为了制作翻页
        if($is_page){
            return $this->success($result);
        }

        return $option->dispaly('pc.on-lists',[],false);
    }

    // 登录
    public function onLogin()
    {
        $user = new UserLogic();
        $info = $user->onLogin();
        if($info === false){
            return $this->error($user->getError());
        }

        session(['uid' => $info['id']]);

        //Cookie::queue(Cookie::make('user', json_encode($info)));

        return $this->success([], '登录成功');
    }

    // 生成Excel
    public function downExcel()
    {
        $option  = $this->optLogic();
        $article = new ArticleLogic();
        $option->setField('rows', 999999);

        // 执行
        $result = $article->explode();

        exit($result);
    }

    // 生成word
    public function makeWord()
    {
        return $this->success([], '生成word成功！');

        $word = new WordLogic();
        $word->makeWord();

        return $this->success([], '生成word成功！');
    }

    // 下载word
    public function downWord()
    {
        return (new WordLogic())->downWord();
    }

    // 股票信息:雪球
    public function stock()
    {
        $url = 'https://xueqiu.com/S/SH600624';
        $ql  = QueryList::get($url)->find('#app .clearfix .stock__main');

        // html
        $html   = $ql->html();
        $encode = mb_detect_encoding($html, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"), true);
        if($encode != 'UTF-8'){
            $html = mb_convert_encoding($html, "UTF-8", $encode); //编码转换为utf-8
        }

        //var_dump($html);
        // html里面的那段json
        $len   = mb_strlen('<stock-operate :quote="');
        $start = mb_strpos($html, '<stock-operate');
        $end   = mb_strpos($html, '</stock-operate>');
        $str   = mb_substr($html, $start + $len, $end - $start - 2 - $len);
        $str   = htmlspecialchars_decode($str);
        $json  = json_decode($str, true);

        $result = [
            'price'      => $json['current'],
            'change'     => $json['chg'],
            'rate'       => $json['percent'],  // eps
            'high'       => $json['high'],
            'open'       => $json['open'],
            'low'        => $json['low'],
            'limit_up'   => $json['limit_up'],  // 涨停
            'limit_down' => $json['limit_down'], // 跌停
            'volume'     => $json['volume'],  // 成交量 （除以100为：手）
            'amount'     => $json['amount'],  // 成交额
            'market'     => $json['market_capital'],
        ];

        return $this->success($result);
    }

    // 股票信息:东方财富网
    public function stockEastmoney()
    {
        // 东方财富网 获取新三板（含市值）
        // https://quote.eastmoney.com/sh600624.html
        $url = 'https://xinsanban.eastmoney.com/api/QuoteCenter/stock/getstockquote?code=600624';

        // 东方财富网 上证股票（不含市值）
        $key  = 'jQuery35107901102841112055_'.LARAVEL_TIME.'499';
        $url  = 'https://94.push2his.eastmoney.com/api/qt/stock/kline/get?cb='.$key.'&secid=1.600624&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20500101&lmt=20&_=1715335363506';
        $curl = new Curl();
        $res  = $curl->url($url)->request();
        $str  = substr($res, strlen($key) + 1, -2);
        $res  = json_decode($str, true);
        if(empty($res)){
            return $this->success();
        }

        $klines = $res['data']['klines'];
        $max    = count($klines) - 1;
        $return = explode(',', $klines[$max]);

        return $this->success($return);
    }

}


